package com.its.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.its.mapper.BusClaimReportMapper;
import com.its.pojo.BusClaimReport;
import com.its.pojo.BusImage;
import com.its.mapper.BusImageMapper;
import com.its.service.BusImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.its.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 朱厚强
 * @since 2024年01月03日
 */
@Service
public class BusImageServiceImpl extends ServiceImpl<BusImageMapper, BusImage> implements BusImageService {
    @Autowired
    private BusImageMapper busImageMapper;
    @Autowired
    private BusClaimReportMapper claimReportMapper;
    @Autowired
    private FastFileStorageClient fastFileStorageClient; // FastDFS 客户端
    @Autowired
    private ThumbImageConfig thumbImageConfig; // 缩略图配置
    @Override
    public Result getByReportId(String reportId) {
        try {
            // 先查询报案号是否正确
            BusClaimReport claimReport = claimReportMapper.selectById(reportId);
            if (claimReport == null){
                return Result.error().message("报案号错误");
            }
            // 查询当前图像
            LambdaQueryWrapper<BusImage> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BusImage::getReportId,reportId);
            List<BusImage> list = busImageMapper.selectList(wrapper);
            // 按照类型分成九分，方便前端好调用。
            List list0 = new ArrayList<>();
            List list1 = new ArrayList<>();
            List list2 = new ArrayList<>();
            List list3 = new ArrayList<>();
            List list4 = new ArrayList<>();
            List list5 = new ArrayList<>();
            List list6 = new ArrayList<>();
            List list7 = new ArrayList<>();
            List list8 = new ArrayList<>();
            // 循环赋值
            list.forEach(l ->{
                if (l.getType() == 0){
                    list0.add(l);
                }
                if (l.getType() == 1){
                    list1.add(l);
                }
                if (l.getType() == 2){
                    list2.add(l);
                }
                if (l.getType() == 3){
                    list3.add(l);
                }
                if (l.getType() == 4){
                    list4.add(l);
                }
                if (l.getType() == 5){
                    list5.add(l);
                }
                if (l.getType() == 6){
                    list6.add(l);
                }
                if (l.getType() == 7){
                    list7.add(l);
                }
                if (l.getType() == 8){
                    list8.add(l);
                }
            });
            // 将所有集合存入map中，方便前端拿值。
            Map<String,Object> map = new HashMap<>();
            map.put("list0",list0);
            map.put("list1",list1);
            map.put("list2",list2);
            map.put("list3",list3);
            map.put("list4",list4);
            map.put("list5",list5);
            map.put("list6",list6);
            map.put("list7",list7);
            map.put("list8",list8);
            return Result.ok().data(map).message("数据采集信息查询完毕");
        } catch (Exception e) {
            System.out.println("数据采集信息查询异常"+e.getStackTrace());
        }
        return Result.error().message("数据采集信息查询失败");
    }

    @Value("${fdfs.view-base-url:}")//加冒号防止为空
    private String viewBaseUrl;
    @Override
    public Result addImg( MultipartFile file , String reportId, Integer type) {
        // 获取文件名称
        String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); // 获取文件后缀名
        try {
            InputStream is = file.getInputStream(); // 获取输入流
            StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(is, file.getSize(), suffix, null); // 上传文件到 FastDFS 分布式文件系统并生成缩略图
            // mysql数据库存储当前图片信息
            BusImage image = new BusImage().setType(type)
                    .setReportId(reportId)
                    // todo 这里的上传人员目前虚拟，后续会有改动
                    .setUploaderId("3")
                    .setUrl(viewBaseUrl + storePath.getFullPath())
                    .setUploadTime(LocalDateTime.now());
            int insert = busImageMapper.insert(image);
            return Result.ok().message("上传成功"); // 返回上传成功的信息
        } catch (IOException e) {
            return Result.ok().message("上传失败"); // 返回上传失败的信息
        }
    }

    @Override
    @Transactional
    public Result delImg(Long id) {
        try {
            // 获取具体的记录
            BusImage image = busImageMapper.selectById(id);
            // 删除fastDFS 里的图片
            busImageMapper.deleteById(id);
            // 删除具体的记录
            fastFileStorageClient.deleteFile(image.getUrl());
            return Result.ok().message("删除成功");
        } catch (Exception e) {
            System.out.println("删除数据采集信息异常"+e.getMessage());
            return Result.error().message("删除失败");
        }
    }
}
